import { Storage, STORAGE_KEYS } from '../utils/storage'
import type { UserInfo } from '../types'

// 全局状态管理
class Store {
  // 用户信息
  private _userInfo: UserInfo | null = null
  // 是否已登录
  private _isLoggedIn: boolean = false
  // 主题
  private _theme: 'light' | 'dark' = 'light'
  // 语言
  private _language: string = 'zh-CN'

  constructor() {
    this.init()
  }

  // 初始化
  private init(): void {
    // 从本地存储恢复状态
    this._userInfo = Storage.get<UserInfo>(STORAGE_KEYS.USER_INFO)
    this._isLoggedIn = !!this._userInfo?.token
    this._theme = Storage.get<'light' | 'dark'>(STORAGE_KEYS.THEME) || 'light'
    this._language = Storage.get<string>(STORAGE_KEYS.LANGUAGE) || 'zh-CN'
  }

  // 用户信息相关
  get userInfo(): UserInfo | null {
    return this._userInfo
  }

  get isLoggedIn(): boolean {
    return this._isLoggedIn
  }

  setUserInfo(userInfo: UserInfo | null): void {
    this._userInfo = userInfo
    this._isLoggedIn = !!userInfo?.token

    if (userInfo) {
      Storage.set(STORAGE_KEYS.USER_INFO, userInfo)
      Storage.set(STORAGE_KEYS.TOKEN, userInfo.token)
      if (userInfo.refreshToken) {
        Storage.set(STORAGE_KEYS.REFRESH_TOKEN, userInfo.refreshToken)
      }
    } else {
      Storage.remove(STORAGE_KEYS.USER_INFO)
      Storage.remove(STORAGE_KEYS.TOKEN)
      Storage.remove(STORAGE_KEYS.REFRESH_TOKEN)
    }
  }

  // 登出
  logout(): void {
    this.setUserInfo(null)
    Storage.clear()
  }

  // 主题相关
  get theme(): 'light' | 'dark' {
    return this._theme
  }

  setTheme(theme: 'light' | 'dark'): void {
    this._theme = theme
    Storage.set(STORAGE_KEYS.THEME, theme)
  }

  // 语言相关
  get language(): string {
    return this._language
  }

  setLanguage(language: string): void {
    this._language = language
    Storage.set(STORAGE_KEYS.LANGUAGE, language)
  }

  // 获取token
  getToken(): string | null {
    return this._userInfo?.token || Storage.get<string>(STORAGE_KEYS.TOKEN)
  }

  // 获取刷新token
  getRefreshToken(): string | null {
    return (
      this._userInfo?.refreshToken ||
      Storage.get<string>(STORAGE_KEYS.REFRESH_TOKEN)
    )
  }
}

// 创建全局状态实例
export const store = new Store()

// 导出类型
export type { UserInfo }
